# coding=utf8
import platform
import json
import urllib.request
import urllib.parse
from platform import node as get_hostname

if platform.system() == 'Linux':
    os_name = 'Linux'
    import linux as osmodule
elif platform.system() == 'Windows':
    os_name = 'Windows'
    import windows as osmodule
else:
    raise Exception('unknown os')

def init():
    global config
    try:
        config = json.load(open('config.json'))
    except OSError:
        config = {'cookie': ''}

def ping():
    data = {
        'hostname': get_hostname(),
        'interfaces': [ {name: mac} for name, mac in osmodule.get_interfaces() ],
        'key': osmodule.get_key(),
        'os': os_name,
    }
    request('ping', cookie=config['cookie'], data=json.dumps(data))

def request(method, **args):
    args = { k.encode('utf8'):v.encode('utf8') for k, v in args.items() }
    print('request', method, args)
    url = 'https://%s/client/%s' % (config['server'], method)
    print('fetching', url)
    req = urllib.request.urlopen(url,
                                 data=urllib.parse.urlencode(args).encode('utf8'))
    return req.read()
    